package services

import (
    //"net/http"
    "github.com/mojocn/base64Captcha"
)

// ConfigJsonBody json request body.
type ConfigJsonBody struct {
    Id            string
	CaptchaType   string
	VerifyValue   string
	DriverAudio   *base64Captcha.DriverAudio // 语音验证码
	DriverString  *base64Captcha.DriverString // 字符验证码
	DriverChinese *base64Captcha.DriverChinese // 中文验证码
	DriverMath    *base64Captcha.DriverMath // 数学验证码(加减乘除)
	DriverDigit   *base64Captcha.DriverDigit // 数字验证码
}

var store = base64Captcha.DefaultMemStore

type CaptchaData struct {
	Key string `json:"key"`
	Src string `json:"src"`
}

func CaptchaEntry() (captchaData CaptchaData, err error) {
    param := ConfigJsonBody {
        Id:          "",
        CaptchaType: "digit",
        VerifyValue: "",
        DriverDigit: &base64Captcha.DriverDigit {
            Height:   80,
            Width:    240,
            Length:   4,
            MaxSkew:  0.7,
            DotCount: 80,
        },
    }
    var driver base64Captcha.Driver

    // 创建base64图像验证码
    //var config interface{}
    switch param.CaptchaType {
        case "audio":
            driver = param.DriverAudio
        case "string":
            driver = param.DriverString.ConvertFonts()
        case "math":
            driver = param.DriverMath.ConvertFonts()
        case "chinese":
            driver = param.DriverChinese.ConvertFonts()
        default:
            driver = param.DriverDigit
    }

    // 生成默认数字
    //driver := base64Captcha.DefaultDriverDigit
    // 生成验证码，同时保存至store
    captcha := base64Captcha.NewCaptcha(driver, store)
    // 生成base64图像验证及id
    id, base64Img, err := captcha.Generate()
    captchaData.Key = id
    captchaData.Src = base64Img
    return
}

func CaptchaCheck(key, code string) bool {
    valid := false
    if store.Verify(key, code, true) {
        valid = true
    }
    return valid
}
